include $(TOPDIR)/core/config/flags.mk
include $(TOPDIR)/core/config/ver.mk

VPATH += $(TOPDIR)/core

SRCS += wrap/wrap.c

BUILDDIR = build

OUTDIR = $(TOPDIR)/out

OBJS := $(subst \,/,$(SRCS))
OBJS := $(OBJS:.c=.o)
OBJS := $(OBJS:.cc=.o)
OBJS := $(OBJS:.cxx=.o)
OBJS := $(OBJS:.cpp=.o)
OBJS := $(OBJS:.CPP=.o)
OBJS := $(OBJS:.c++=.o)
OBJS := $(OBJS:.C=.o)
OBJS := $(OBJS:.s=.o)
OBJS := $(OBJS:.S=.o)
OBJS := $(OBJS:.sx=.o)
OBJS := $(addprefix $(BUILDDIR)/,$(OBJS))

OBJSDIR = $(patsubst %/,%,$(dir $(OBJS)))

all: $(OUTDIR)/app.bin

$(OUTDIR)/app.bin: $(OUTDIR)/app.elf
	@echo --- Target $(notdir $@) ---
	@$(OBJCOPY) -O binary $< $@
	@echo --- Success ---

$(OUTDIR)/app.elf: $(OBJS)
	@echo --- Linking $(notdir $@) ---
	$(CC) $(LDFLAGS) -T $(LINK_SCRIPT) -Wl,-Map=$(OUTDIR)/app.map -o $@ $^ $(EXTRA_LIBS) $(SDK_LIBS)
	@$(SIZE) $@

$(BUILDDIR)/%.o: %.c
	@echo --- Compiling $(notdir $<) ---
	$(CC) $(CFLAGS) -MMD -c -o $@ $<

$(BUILDDIR)/%.o: %.s
	@echo --- Compiling $(notdir $<) ---
	$(CC) $(CFLAGS) -MMD -c -o $@ $<

$(BUILDDIR)/%.o: %.cxx
	@echo --- Compiling $(notdir $<) ---
	$(CXX) $(CXXFLAGS) -MMD -c -o $@ $<

$(BUILDDIR)/%.o: %.cpp
	@echo --- Compiling $(notdir $<) ---
	$(CXX) $(CXXFLAGS) -MMD -c -o $@ $<

$(OBJS): | $(OBJSDIR)
$(OBJSDIR):
	-@$(MKDIR) $(subst /,\,$@)

clean:
	@echo --- clean $(BUILDDIR) ---	
	-@$(RMDIR) $(BUILDDIR)
	

.PHONY: all clean

-include $(OBJS:.o=.d)